package base.jfinal.plugin;

import java.text.ParseException;

import org.apache.log4j.Logger;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.IPlugin;

/**
 * 定时器插件
 * @author Administrator
 *
 */
public class QuartzPlugin implements IPlugin {

	private Logger log4j = Logger.getLogger(QuartzPlugin.class);
	private JSONArray l_jsons;
	//private SchedulerFactory sf = null;
	private static Scheduler sched = null;
	  
	public QuartzPlugin(JSONArray jsons) {
		l_jsons=jsons;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public boolean start() {
		try {
			getScheduler();
			JSONObject json;
			for (int i = 0; i < l_jsons.size(); i++) {
				json=l_jsons.getJSONObject(i);
				log4j.warn(json.getString("ClassSpace"));
				//服务是否需要启动
				if(!json.getBoolean("Enable")) continue;
				
				Class clz=Class.forName(json.getString("ClassSpace"));
				
				JobDetail job =JobBuilder.newJob(clz).withIdentity(json.getString("ClassSpace")).build();
				CronTrigger trigger =TriggerBuilder.newTrigger().withIdentity(json.getString("ClassSpace"))
						.withSchedule(CronScheduleBuilder.cronSchedule(json.getString("Cron"))).build();
				sched.scheduleJob(job, trigger);
				sched.start();
			}
		} catch (SchedulerException | ParseException|ClassNotFoundException e) {
			return false;
		}
		return true;
	}

	@Override
	public boolean stop() {
		try {
			sched.shutdown();
	    } catch (SchedulerException e) {
	    	return false;
	    }
		return true;
	}

	public static Scheduler getScheduler(){
		if(sched==null){
			try {
				sched =StdSchedulerFactory.getDefaultScheduler();
			} catch (SchedulerException e) {
				new RuntimeException(e);
			}
		}
		return sched;
	}
}
